package com.wfh.mianshiji.ws;

import com.wfh.mianshiji.model.dto.interview.InterviewStopRequest;
import com.wfh.mianshiji.service.InterviewService;
import com.wfh.mianshiji.ws.handler.MessageRouter;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.*;
import org.springframework.web.socket.handler.AbstractWebSocketHandler; // ← 修改这里

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author fenghuanwang
 */
@Slf4j
@Component
public class InterviewWebSocketHandler extends AbstractWebSocketHandler {

    private static final Map<String, WebSocketSession> SESSION_MAP = new ConcurrentHashMap<>();

    @Resource
    private MessageRouter messageRouter;

    @Resource
    private InterviewService interviewService;


    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        Long userId = (Long) session.getAttributes().get("userId");
        Long interviewId = (Long) session.getAttributes().get("interviewId");

        String key = buildKey(userId, interviewId);
        SESSION_MAP.put(key, session);

        log.info("用户 {} 进入面试 {}，连接建立", userId, interviewId);
    }

    /**
     * 处理文本消息
     * @param session
     * @param message
     * @throws Exception
     */
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        Long userId = (Long) session.getAttributes().get("userId");
        if (userId == null) {
            session.close(CloseStatus.POLICY_VIOLATION);
            return;
        }
        messageRouter.route(message.getPayload(), session);
    }

    /**
     * 处理二进制数据
     * @param session
     * @param message
     * @throws Exception
     */
    @Override
    protected void handleBinaryMessage(WebSocketSession session, BinaryMessage message) throws Exception {
        // 不做任何处理，但允许接收二进制数据而不报错
        // 如果你后续需要处理，再在这里加逻辑
    }

    /**
     * 连接关闭之后
     * @param session
     * @param status
     * @throws Exception
     */
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        Long userId = (Long) session.getAttributes().get("userId");
        Long interviewId = (Long) session.getAttributes().get("interviewId");
        if (userId != null && interviewId != null) {
            String key = buildKey(userId, interviewId);
            SESSION_MAP.remove(key);
            log.info("用户 {} 面试 {} 连接关闭", userId, interviewId);
            // 连接关闭之后，默认认为当前用户结束了面试
            InterviewStopRequest stopRequest = new InterviewStopRequest();
            stopRequest.setUserId(userId);
            stopRequest.setInterviewId(interviewId);
            stopRequest.setMessage("结束");
            interviewService.stop(stopRequest);
        }
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        log.error("WebSocket 传输错误", exception);
        session.close(CloseStatus.SERVER_ERROR);
    }

    private String buildKey(Long userId, Long interviewId) {
        return userId + ":" + interviewId;
    }

    public static void sendTo(Long userId, Long interviewId, String msg) {
        WebSocketSession session = SESSION_MAP.get(userId + ":" + interviewId);
        if (session != null && session.isOpen()) {
            try {
                session.sendMessage(new TextMessage(msg));
            } catch (Exception e) {
                log.error("推送消息失败", e);
            }
        }
    }
}